package net.meblabs.bookapp.web.controller;

import java.util.ArrayList;
import java.util.List;

import net.meblabs.bookapp.data.Hint;
import net.meblabs.bookapp.data.dao.BookDao;
import net.meblabs.bookapp.data.model.Author;
import net.meblabs.bookapp.data.model.Book;
import net.meblabs.bookapp.util.ServiceLoaderUtil;
import net.meblabs.bookimp.AuthorImporter;

import org.apache.commons.collections.Factory;
import org.apache.commons.collections.list.LazyList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/book")
public class BookController {

	@Autowired
	private BookDao bookDao;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView getBooks() {
		List<Book> books = bookDao.find();
		ServiceLoaderUtil.load(AuthorImporter.class);
		ModelAndView mav = new ModelAndView("books");
		mav.addObject("books", books);
		return mav;
	}

	@RequestMapping("/{id}")
	public String getBook(@PathVariable("id") Long id, Model model) {
		Book book = bookDao.findById(id);
		model.addAttribute("book", book);
		return "book";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Book book, BindingResult result, Model model) {
		if (result.hasErrors()) {
			model.addAttribute("message", "Niepoprawne wartości");
			return "saveBook";
		} else {
			try {
				bookDao.save(book);
				return "redirect:/books";
			} catch (Exception e) {
				e.printStackTrace();
				model.addAttribute("message", e.getMessage());
				return "saveBook";
			}
		}
	}

	@RequestMapping(value = "/save", method = RequestMethod.GET)
	public String save(Model model) {
		Book book = new Book();
		@SuppressWarnings("unchecked")
		List<Author> authors = LazyList.decorate(new ArrayList<Author>(), new Factory() {

			@Override
			public Object create() {
				return new Author();
			}
		});
		book.setAuthors(authors);
		model.addAttribute("book", book);
		return "saveBook";
	}

	@RequestMapping("/ajax")
	public @ResponseBody
	List<Hint> authorsAutocomplete(@RequestParam("term") String term) {
		return bookDao.findAuthorsAutocomplete(term);
	}
}
